package br.ufrn.imd.classificados.tasks;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListView;
import br.ufrn.imd.classificados.adapter.ItemAdapter;
import br.ufrn.imd.classificados.dominio.Item;
import br.ufrn.imd.imd0023_classificados.R;

/**
 * HTTP GET requests to the REST API.
 * @author Reginaldo Silva
 *
 */
public class ApiGetItemsTask extends AsyncTask<String, Void, List<Item>> {

	String endpoint;
	Context context;

	public ApiGetItemsTask(String endpoint, Context context) {
		this.endpoint = endpoint;
		this.context = context;
	}

	protected List<Item> doInBackground(String... params) {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://arcane-atoll-4224.herokuapp.com/" + this.endpoint + params[0]);
        List<Item> items = null;

        try {
	        HttpResponse response = httpClient.execute(request);
	        HttpEntity entity = response.getEntity();

	        if (entity != null) {
	        	InputStream stream = entity.getContent();	        	
	        	String json = toString(stream);	        	
	        	stream.close();
	        	items = getItems(json);
	        }
        } catch (ClientProtocolException e) {
			e.printStackTrace();
			Log.i("Client Protocol Exception", e + "");
		} catch (IOException e) {
			e.printStackTrace();
			Log.i("IO Exception", e + "");
		}

        return items;
	}

	protected void onPostExecute(List<Item> result) {
		ArrayList<Item> sellingList = new ArrayList<Item>();
		ArrayList<Item> buyingList = new ArrayList<Item>();

		for (int i = 0; i < result.size(); i++) {
			Item item = (Item) result.get(i);
			if (item.getVendendo()) {
				sellingList.add(item);
			} else {
				buyingList.add(item);
			}
		}

		ItemAdapter adapterListViewSelling = new ItemAdapter(context, sellingList);
		ItemAdapter adapterListViewBuying = new ItemAdapter(context, buyingList);

		ListView listViewSelling = (ListView) (((Activity) context).findViewById(R.id.itens_1));
		ListView listViewBuying = (ListView) (((Activity) context).findViewById(R.id.itens_2));
		
		listViewSelling.setAdapter(adapterListViewSelling);
		listViewBuying.setAdapter(adapterListViewBuying);
	}

	private List<Item> getItems(String jsonStr) {
		List<Item> result = new ArrayList<Item>();

		try {
			JSONObject jsonObj = new JSONObject(jsonStr);
			JSONArray items = jsonObj.getJSONArray("items");

			for (int i = 0; i < items.length(); i++) {
				JSONObject item = items.getJSONObject(i);

				Item pojo = new Item(
					item.getInt("id"),
					item.getString("title"),
					item.getString("description"),
					item.getDouble("value"),
					item.getBoolean("selling")
				);
				result.add(pojo);
			}
		} catch (JSONException e) {
			e.printStackTrace();
			Log.i("JSON Exception", e + "");
		}
		return result;
	}

	private String toString(InputStream is) throws IOException {
		byte[] bytes = new byte[1024];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int lidos;
		while ((lidos = is.read(bytes)) > 0) {
			baos.write(bytes, 0, lidos);
		}
		return new String(baos.toByteArray());
	}
}
